import { ERROR_CODE_MAP, BASE_URL } from './constant'
import { logoutLocal } from '@/hook/useWechatUser';
import Taro from '@tarojs/taro'

// 获取运行环境
const env = Taro.getAccountInfoSync().miniProgram.envVersion
const baseUrl = BASE_URL[env]

const request = (url, data, method = "", options = {}) => {
  return new Promise((resolve, reject) => {
    const { loading } = options;

    loading !== false && Taro.showLoading({
      title: '处理中，请稍后~',
      mask: true
    });

    const header = {
      'Content-Type': 'application/json',
      token: Taro.getStorageSync('token') || '',
      Authorization: Taro.getStorageSync('token') || ''
    };

    Taro.request({
      url: baseUrl + url,
      data: data,
      method: method || 'POST',
      header,
      success: (res) => {
        Taro.hideLoading();
        const { data, statusCode } = res;

        if (statusCode !== 200) {
          Taro.showToast({
            title: `请求接口失败，url:${url}`,
            icon: 'none'
          })
          reject(res);
          return;
        }

        const { ret } = data;

        if (ret === ERROR_CODE_MAP.unauthorized || ret === ERROR_CODE_MAP.unLogin) {
          Taro.showToast({
            title: `登录失效, 请重新登录`,
            icon: 'error'
          });
          logoutLocal();
          reject(data);
          return;
        }

        resolve(data);
      },
      fail: (err) => {
        Taro.hideLoading();
        console.error('接口请求异常==============>: ', err);
        Taro.showToast({
          title: '网络请求失败，请稍后重试',
          icon: 'none'
        });
        reject(err);
      },
      complete: () => {
        loading !== false && Taro.hideLoading();
      }
    });
  });
}

const get = (url, params, options) => request(url, params, "GET", options);
const put = (url, data, options) => request(url, data, "PUT", options);
const post = (url, data, options) => request(url, data, "POST", options);

export {
  get,
  put,
  post
}
